<?php
/**
 * Created by PhpStorm.
 * User: wttfire
 * Date: 2020/12/29
 * Time: 上午11:03
 */
namespace app\api\controller;

use app\common\controller\Api;
use think\Request;
use app\api\controller\Standard as SDApi;
use app\api\model\Standard as SDModel;
use app\api\model\GroupToursLine as GTModel;

class FliggyApi extends Api{

    private $itemTypes = [];
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->itemTypes = [
            '境内跟团游'=>'DomesticGroupTour',
            '出境跟团游'=>'OverseasGroupTour',
            '境内自由行'=>'DomesticSelfGuidedTour',
            '出境自由行'=>'OverseasSelfGuidedTour',
            '境内当地玩乐'=>'DomesticLocalFun',
            '境外当地玩乐'=>'OverseasLocalFun',
            '境内邮轮'=>'DomesticCruise',
            '国际邮轮'=>'InternationalCruise',
            '门票'=>'Tickets',
            '同城活动'=>'CityActivity',
            '境外玩乐套餐'=>'OverseasFunPackage',
        ];
    }

    //获取产品接口的信息
    public function getProductInfo()
    {
        $post = request()->post();
        $product_id = $post['productId']??0;
        if(empty($product_id)){
            $standard_id = $post['standardId']??0;
            $standardInfo = db('standard')->find($standard_id);
            $standardTrip = db('standardtrip')->where(['sid'=>$standard_id])->find();
            if(empty($standardTrip['trip_id'])){
                return json_encode(['code'=>400,'msg'=>'未查询到相关产品']);
            }
            $product_id = $standardTrip['trip_id'];
        }else{
            $standardTrip = db('standardtrip')->where(['trip_id'=>$product_id])->find();
            if(!empty($standardTrip['sid'])) $standardInfo = db('standard')->find($standardTrip['sid']);
        }

        $productInfo = db('product')->find($product_id);
        if(empty($productInfo)) return json_encode(['code'=>400,'msg'=>'未查询到相关产品']);
        $goodsInfo = db('goods')->where(['goods_tcode'=>$productInfo['item_num']])->find();

        $result['created'] = date('Y-m-d H:i:s',$productInfo['create_time']);
        $result['modified'] = date('Y-m-d H:i:s',$productInfo['update_time']);
        if(!empty($productInfo['start_city'])) $startCity = db('city')->find($productInfo['start_city']);
        if(!empty($productInfo['end_city'])) $endCity = db('city')->find($productInfo['end_city']);
        if(!empty($productInfo['service_type'])) $serviceType = db('service_type')->field('name,type')->find($productInfo['service_type']);
        $product_ota = db('product_ota')->where(['product_id'=>$product_id])->find();
        $ota_images = !empty($product_ota['ota_images']) ? explode(',',$product_ota['ota_images']) : [];
        $cancel_rules = !empty($product_ota['cancel_rules']) ? explode(',',$product_ota['cancel_rules']) : [];
        $result = [
            'standardId'=>$standardTrip['sid']??'',
            'standardType'=>$standardInfo['type']??'',
            'standardTypeName'=>(new SDModel())->getTypeName($standardInfo['type']),
            'city'=>$startCity['name']??'',
            'desc'=>!empty($productInfo['is_text_plan'])?$productInfo['text_plan']:$productInfo['sale_details'],
            'from_city'=>$startCity['name']??'',
            'to_city'=>$endCity['name']??'',
            'product_code'=>$productInfo['item_num']??'',
            'pic_urls'=>!empty($goodsInfo['goods_image']) ?
                array_values(array_filter(explode(',',$goodsInfo['goods_image']))) : [],
            'video_url'=>!empty($goodsInfo['goods_video']) ? $goodsInfo['goods_video'] : '',
            'sub_titles'=>$productInfo['product_sub_title'],
            'title'=>$productInfo['name'],
            'trip_max_days'=>$productInfo['days'],
            'need_confirm'=>!empty($goodsInfo['need_confirm']) ? true : false,
            'service_language'=>!empty($productInfo['service_language']) ? 'english' : 'chinese',
            'customer_content'=>!empty($productInfo['customer_content']) ?
                json_decode($productInfo['customer_content'],true) : [],
            'order_type'=>!empty($serviceType) ?
                $serviceType : new \ArrayObject(),
            'fee_included'=>$productInfo['price'],
            'fee_excluded'=>$productInfo['priceno'],
            'item_careful'=>$productInfo['careful'],
            'rules_return_reform'=>$productInfo['back'],
            'ota_price_out'=>$productInfo['ota_price_out'],
            'ota_price_busy'=>$productInfo['ota_price_busy'],
            'cost_price_out'=>$productInfo['cost_price_out'],
            'cost_price_busy'=>$productInfo['cost_price_busy'],
            'special_intro'=>$productInfo['introduction'],
            'duration'=>$standardTrip['endDays']??0,//至少提前天数 最晚成团提前天数
            'ota_images'=>$ota_images,
            'ota_cancel_rules'=>$cancel_rules,
            'sale_type'=>$product_ota['sale_type'],
            'bc_start_date'=>!empty($product_ota['bc_start_date']) ?
                date('Y-m-d H:i:s',$product_ota['bc_start_date']) : '',
            'start_combo_date'=>!empty($product_ota['start_combo_date']) ?
                date('Y-m-d H:i:s',$product_ota['start_combo_date']) : '',
            'end_combo_date'=>!empty($product_ota['end_combo_date']) ?
                date('Y-m-d H:i:s',$product_ota['end_combo_date']) : '',
            'has_invoice'=>empty($product_ota['has_invoice']) ? true : false,
            'has_discount'=>empty($product_ota['has_discount']) ? true : false,
            'has_showcase'=>empty($product_ota['has_showcase']) ? true : false,
        ];
        $result['allCustomerInfoReq'] = !empty($productInfo['all_customer_req']) ? true : false;
        $customer_info_config = $productInfo['customer_info_config']??'';
        $result['customerInfoConfig'] = (new SDModel())->getProductCustomerInfoConfig($customer_info_config);

        $tripData = (new GTModel())->getProductSchedules($product_id);
        $result['ref_trip'] = $tripData['child'] ?? [];
        $result['tripDestination'] = $tripData['tripDestination'] ?? [];
        $result['itemType'] = [
            'key'=>$this->itemTypes[$product_ota['item_type']] ?? '',
            'value'=>$product_ota['item_type'] ?? ''
        ];
        //针对门票类型 单独获取数据
        $result['ticketsInfo'] = $this->getProductOtaTicketConfig($product_id);

        return json_encode(['code'=>200,'msg'=>'success','data'=>$result]);
    }

    //获取产品套餐到OTA
    public function getStandardPackageSpecs()
    {
        $post = request()->post();
        //鉴权
        $auth_res = (new SDApi())->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standard_id = $post['standardId']??0;
        $supplier_id = $post['supplierId']??'';
        //判断是否供应商采购商同账号
        $model = new SDModel();
        $details = $model->getGoodsPackageSpecsToOTA($standard_id,$supplier_id);
        if(!empty($details)){
            //存在错误 会返回 code 码
            if(isset($details['code'])){
                return json_encode($details);
            }else{
                return json_encode(['code'=>200,'msg'=>'获取成功','data'=>$details]);
            }
        }else{
            return json_encode(['code'=>400,'msg'=>'data is empty']);
        }
    }

    //获取允许上架的产品列表 用于新建OTA的商品模型
    public function getStandardListToOTA($standard_id=0,$page=1,$pagelimit=10)
    {
        $post = request()->post();
        //鉴权
        $auth_res = (new SDApi())->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        //增加筛选条件
        $keyword = !empty($post['keywords'])?trim($post['keywords']):'';
        $cityKbxIds = $post['cityIds']??[];
        $countryKbxIds = $post['countryIds']??[];
        $continentIds = $post['continentIds']??[];
        $tagIds = $post['tagIds']??[];
        $supplier_id = $post['supplierId']??'';
        $agentSupplierId = $post['agentSupplierId']??"";//分销商对应的供应商ID
        //$authenticated = $post['authenticated']??true;//是否有资质
        $except_ids = $post['exceptIds']??[];
        //关键词搜索
        if(!empty($keyword)) $where['s.id|s.name|g.goods_tcode'] = ['like','%'.$keyword.'%'];
        //出发城市
        if(!empty($cityKbxIds)){//城市级筛选
            $cityIds = db('city')->where(['kbx_id'=>['in',$cityKbxIds]])->column('id');
            if(!empty($cityIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
        }elseif(!empty($countryKbxIds)){//国家级筛选
            $countryIds = db('city')->where(['kbx_id'=>['in',$countryKbxIds]])->column('id');
            if(!empty($countryIds)){
                $cityIds = db('city')->where([
                    'groupid'=>['in',$countryIds],
                    'deleted'=>0,
                    'type'=>'CITY'
                ])->column('id');
                if(!empty($countryIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
            }
        }elseif(!empty($continentIds)){//洲级筛选
            $cityIds = db('city')->where([
                'continentid'=>['in',$continentIds],
                'deleted'=>0,
                'type'=>'CITY'
            ])->column('id');
            if(!empty($cityIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
        }
//        var_dump($cityIds);exit;
        //分类类型
        if(!empty($tagIds)){
            $standard_ids = (new SD())->getStandardIdsBytagIds($tagIds);
            $where['s.id'] = ['in',$standard_ids];
        }
        //排除已选产品
        //if(!empty($except_ids)) $where['s.id'] = ['not in',$except_ids];

        //采购商可采购所有通用的产品 有供应商的也可采购自营的产品
        $aegnt_supplier_admin_ids = "";
        if(!empty($agentSupplierId)){
            //分销商对应供应商的信息
            $aegnt_supplier_admin_ids = $this->getSupplierAdminIds($agentSupplierId);
        }
        //情况1 有供应商
        if(!empty($agentSupplierId) && !empty($aegnt_supplier_admin_ids)){//有供应商 自营+通用
            //分销商对应供应商的信息
            //自己的产品 和 其他供应商允许售卖的产品
            // supplier_admin_id in (aegnt_supplier_admin_ids) or (supplier_admin_id not in (aegnt_supplier_admin_ids) and allow_everyone_quote=1)
            $aegnt_supplier_admin_ids = implode(',',$aegnt_supplier_admin_ids);
            $where[] = new Expression('s.supplier_admin_id in ('.$aegnt_supplier_admin_ids.') or (s.supplier_admin_id not in ('.$aegnt_supplier_admin_ids.') and s.allow_everyone_quote=1)');

        }elseif(!empty($supplier_id)){//查询特定供应商产品
            //获取管理员ID
            $supplier_admin_ids = $this->getSupplierAdminIds($supplier_id);
            if(!empty($supplier_admin_ids)){
                $where['s.supplier_admin_id'] = ['in',$supplier_admin_ids];
            }
            $where['s.allow_everyone_quote'] = 1;//其他供应商允许售卖的产品
        }else{//无供应商 通用
            $where['s.allow_everyone_quote'] = 1;//其他供应商允许售卖的产品
        }

        $standardModel = new SDModel();
        $from = 'orderSystem';
        $where['s.status'] = 1;//启用的标品
        $where['s.is_deleted'] = 0;//未删除的标品
        $where['s.show_toB'] = 1;//用于toB的标品
//        $topCate = (new SD())->getStandardTopCates();
//        $topCateIds = array_column($topCate,'id');
//        $where['s.topCate'] = ['in',$topCateIds];
        //是否允许其他人采购

        if(!empty($standard_id)) $where['s.id'] = $standard_id;//刷新单条数据
        $total = db("standard s")->join("goods g",'g.goods_id=s.goods_id','left')
            ->join("standardtrip st",'st.sid=s.id','left')
            ->where($where)->count();
        $list = db("standard s")
            ->where($where)
            ->join("goods g",'g.goods_id=s.goods_id','left')
            ->join("standardtrip st",'st.sid=s.id','left')
            ->join("city c",'c.id=st.startCityId','left')
            ->join("supplier_admin admin",'admin.supplier_admin_id=s.supplier_admin_id','left')
            ->field('s.id as standardId,s.name as standardName,s.type as standardType,introduce as subTitle,showImg,
            g.goods_id,g.goods_name,g.orderType,is_recommend,trip_id,
            st.startCityId,c.name as startCityName,c.kbx_id as kbxStartCityId,
            days,endDays,subType,toursLineTitle,specialInfo,topCate,admin.company_id as supplierId')
            ->order("s.is_recommend desc,s.id desc")
            ->page($page,$pagelimit)
            ->select();
//        var_dump($list);exit;
//        var_dump(db()->getLastSql());exit;
        foreach ($list as $key=>$value){
            $list[$key]['id'] = $value['standardId'];
            $list[$key]['goods_name'] = $value['standardName'];
            $list[$key]['standardTypeName'] = $standardModel->getTypeName($value['standardType']);
            $list[$key]['classificationTags'] = $standardModel->getStandardTags($value['standardId']);
            $list[$key]['subType'] = $standardModel->getSubType($value['subType']);
            $list[$key]['isSelected'] = !empty($except_ids)&&in_array($value['standardId'],$except_ids)?true:false;
            //获取关联的商品信息
            $list[$key]['goodsInfo'] = [];
            $list[$key]['showImg'] = "";
            if(!empty($value['goods_id'])){
                $list[$key]['goodsInfo'] = $standardModel->getLinkGoodsInfo($value['goods_id'],$value['standardId'],$from);
                $image = $list[$key]['goodsInfo']['small_image']??[];
                $list[$key]['showImg'] = $standardModel->checkImgUrl($image[0]??"")??"";
//                $list[$key]['showImg'] = (new SD())->batchOssImgUrl($list[$key]['showImg']);
                $list[$key]['goodsprice'] = floatval($list[$key]['goodsInfo']['goodsprice'])??0;
                $list[$key]['salesVolume'] = $list[$key]['goodsInfo']['goodssales']??"0";
                unset($list[$key]['goodsInfo']['small_image']);
                $list[$key]['startCityId'] = $value['startCityId']?:$list[$key]['goodsInfo']['city_id'];
                $list[$key]['startCityName'] = $value['startCityName']?:$list[$key]['goodsInfo']['cityName'];
                $list[$key]['kbxStartCityId'] = $value['kbxStartCityId']?:$list[$key]['goodsInfo']['kbxCityId'];
                $list[$key]['tags'] = !empty($list[$key]['goodsInfo']['tags'])?
                    array_merge($list[$key]['classificationTags'],$list[$key]['goodsInfo']['tags']):
                    $list[$key]['classificationTags'];
            }
        }
        $result['pageInfo'] = [
            'totalNum'=>$total,
            'totalPage'=>ceil($total/$pagelimit),
            'page'=>(int)$page,
            'pagelimit'=>(int)$pagelimit,
        ];
        $result['list'] = $list;
        //返回json 数据
        return $this->result('success',$result,200,'json');
    }

    //订单系统采购商 获取上架的B端产品日历价格
    public function getStandardSpecTimeToOTA()
    {
        $post = request()->post();
        //鉴权
        $auth_res = (new SDApi())->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standard_id = $post['standardId']??0;
        $supplier_id = $post['supplierId']??'';
        $year = $post['year']??'';
        $month = $post['month']??'';
        $duration = $post['duration']??1;
        $model = new SDModel();
        $details = $model->getGoodsSpecToOTA($standard_id,$year,$month,$duration,$supplier_id);
        if(!empty($details)){
            //存在错误 会返回 code 码
            if(isset($details['code'])){
                return json_encode($details);
            }else{
                return json_encode(['code'=>200,'msg'=>'获取成功','data'=>$details]);
            }
        }else{
            return json_encode(['code'=>400,'msg'=>'data is empty']);
        }
    }

    //返回OTA 门票产品配置
    public function getProductOtaTicketConfig($product_id)
    {
        $result = new \ArrayObject();
        if(empty($product_id)) return $result;
        $product = db('product')->where([
            'id'=>$product_id,
            'service_type'=>2,
        ])->find();
        if(empty($product)) return $result;
        $product_ota_ticket = db('product_ota_ticket')
            ->where([
            'product_id'=>$product_id
        ])->find();
        if(empty($product_ota_ticket)) return $result;

        $product_ota_ticket['reserve_limit_rule'] = $this->getProductOTATicketReserveLimitRules($product_ota_ticket);
        return $product_ota_ticket;
    }
    //返回OTA 门票产品的预定时间限定规则
    public function getProductOTATicketReserveLimitRules($otaTicketConfig)
    {
        //预定时间限定类型为有限制时生效
        if(empty($otaTicketConfig['reserve_limit_type']) ||
            $otaTicketConfig['reserve_limit_type'] < 2){
            return '';
        }
        $rules = '';
        $per_time = $enter_time = [];
        if(!empty($otaTicketConfig['reserve_limit_per_time'])){
            $per_time = explode(':',$otaTicketConfig['reserve_limit_per_time']);
        }

        if(!empty($otaTicketConfig['reserve_limit_enter_time'])){
            $enter_time = explode(':',$otaTicketConfig['reserve_limit_enter_time']);
        }

        $rules[] = $otaTicketConfig['reserve_limit_day'] ?? 0;
        $rules = array_merge($rules,$per_time,$enter_time);
        return implode('_',$rules);
    }

    //获取分类
    public function getItemTypes()
    {
        return $this->itemTypes;
    }

}